package logger

import "go.uber.org/zap/zapcore"

type (
	interceptorCore struct {
		interceptor func(entry zapcore.Entry) error
		core        zapcore.Core
	}
)

func newInterceptorCore(core zapcore.Core, interceptor func(entry zapcore.Entry) error) zapcore.Core {
	return &interceptorCore{
		core:        core,
		interceptor: interceptor,
	}
}

func (c *interceptorCore) Enabled(l zapcore.Level) bool {
	return c.core.Enabled(l)
}

func (c *interceptorCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
	if c.interceptor != nil {
		if err := c.interceptor(entry); err != nil {
			return err
		}
	}
	return c.core.Write(entry, fields)
}

func (c *interceptorCore) With(fields []zapcore.Field) zapcore.Core {
	return newInterceptorCore(c.core, c.interceptor).With(fields)
}

func (c *interceptorCore) Check(entry zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
	if c.Enabled(entry.Level) {
		return ce.AddCore(entry, c)
	}
	return ce
}

func (c *interceptorCore) Sync() error {
	return c.core.Sync()
}
